#!/usr/bin/env python

"""Erlang compile script for ASN1Library

Usage:  compile.py target

Argument 'target' can have one of the following values:
  - asn1     : compile protocols
  - main     : compile all erlang code under src
  - all      : compile all
  
TODO: change to use subprocess to support paths with whitespace
"""
import os
import sys

ERLANG_COMPILER = "erlc"
ROOT_PATH = os.path.dirname(__file__)
ERLANG_SOURCE = os.path.join(ROOT_PATH, 'src', 'erlang', '*.erl')
UTEST_SOURCE = os.path.join(ROOT_PATH, 'utests', 'resources', '*.erl')

ASN1_BASE = os.path.join(ROOT_PATH, 'src', 'asn1')
PROTOCOLS = [os.path.join(ASN1_BASE, protocol, '*.asn1') 
             for protocol in os.listdir(ASN1_BASE) if not protocol.startswith('.')]

BUILD_OUT = os.path.join(ROOT_PATH, 'ebin')

def main():
    _check_path()
    cmd = '%s -o %s %s' % (ERLANG_COMPILER, BUILD_OUT, ERLANG_SOURCE)
    _compile(cmd)

def asn1():
    _check_path()
    for protocol in PROTOCOLS:
        cmd = '%s -o %s -b per_bin +optimize %s' % (ERLANG_COMPILER, BUILD_OUT, protocol)
        _compile(cmd)

def _compile(cmd):
    print "Compiling:"
    print cmd
    rc = os.system(cmd)
    if rc != 0:
        print "Compilation failed."
        sys.exit(1)

def all():
    main()
    asn1()

def _check_path():
    if not os.path.exists(BUILD_OUT):
        os.mkdir(BUILD_OUT)

if __name__ == '__main__':
    try:
        globals()[sys.argv[1]](*sys.argv[2:])
    except (KeyError, IndexError, TypeError, ValueError):
        print __doc__
